package com.lanou3g.hw0512;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Properties;

/**
 * Created by dllo on 18/5/12.
 */
@WebServlet(name = "AServlet", urlPatterns = "/a")
public class AServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取前端传过来的参数
        String user = request.getParameter("user");
        System.out.println(user);
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            Properties properties = new Properties();
            //使用类名.class.getClassLoader()
            //获取类加载器
            //类加载器的getResourceAsStream
            //是相对于src路径下的
            InputStream is = AServlet.class.getClassLoader().getResourceAsStream("jdbc.properties");
            properties.load(is);
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/lanou_news", properties);
            String sql = "SELECT * FROM my_news WHERE title LIKE ?";
            PreparedStatement statement = conn.prepareStatement(sql);
            statement.setString(1, "%" + user + "%");
            ResultSet rs = statement.executeQuery();
            PrintWriter writer = response.getWriter();
            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                writer.println("用户要的是:" + id + "-" + title);
                writer.println("<br>");
            }
            rs.close();
            statement.close();
            conn.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}